package com.eroad.product.tools;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;

/**
 * 柱状图控件
 * 
 */
public class HistogramView extends View {
	/** 控件宽度 */
	private float viewWidth; //
	/** 控件高度 */
	private float viewHeight; //

	private String[] xData;
	private String[] yData;

	/** 坐标线画笔 */
	private Paint linePaint; //
	/** 文本画笔 */
	private Paint textPaint; //
	/** 柱状图画笔 */
	private Paint dataPaint; //
	/** 选中之后的背景 */
	private Paint selectBkgPaint; //
	/** 屏幕密度 */
	private float density; //
	/** x轴长度 */
	private float xLength; //
	/** y轴长度 */
	private float yLength; //
	/** x原点 */
	private float xPoint; //
	/** y原点 */
	private float yPoint; //
	/** 边距 */
	private float border = 40; //
	/** x轴刻度长度 */
	private float xScale; //
	/** y轴刻度长度 */
	private float yScale; //
	/** y刻度数量 */
	private int yScaleNum = 6; //
	/** 字体大小 */
	private float textSize; //
	/** y刻度 */
	private float eachYLable; //
	/** y轴单位 */
	private String yunit = "h"; //
	private DecimalFormat df = new DecimalFormat("0.0");
	/** 当前手指位置 */
	private int currentX; //
	/** 点击柱状图的回调 */
	private OnGraphItemClickListener listener; //

	public HistogramView(Context context) {
		super(context);
	}

	public HistogramView(Context context, AttributeSet attrs) {
		super(context, attrs);
		Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
		DisplayMetrics displayMetrics = new DisplayMetrics();
		display.getMetrics(displayMetrics);
		density = displayMetrics.density;
	}

	public HistogramView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	/**
	 * 为柱状图设置数据
	 * 
	 * @param xData
	 *            字符串数组，表示X轴数据
	 * @param yData
	 *            字符串数组，字符串形式的Float
	 */
	public void setData(String[] xData, String[] yData, String yUnit) {
		this.xData = xData;
		this.yData = yData;
		this.yunit = yUnit;
		postInvalidate();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		viewWidth = getWidth();
		viewHeight = getHeight();
		initData(); // 初始化坐标轴数据
		initPaint(); // 初始化所有画笔

		// Y轴
		canvas.drawLine(xPoint, border, xPoint, viewHeight - yPoint, linePaint);
		// X轴
		canvas.drawLine(xPoint, viewHeight - yPoint, viewWidth - border, viewHeight - yPoint, linePaint);
		// 平行X轴的标线
		for (int i = 0; i < yScaleNum; i++) {
			canvas.drawLine(xPoint, viewHeight - yPoint - ((i + 1) * yScale), viewWidth - border, viewHeight - yPoint
					- ((i + 1) * yScale), linePaint);
			// Y轴的刻度值,值为平均分配之后算出来的
			canvas.drawText(df.format(BigDecimal.valueOf(eachYLable * (i + 1))) + yunit, 3 * density, viewHeight - yPoint
					- ((i + 1) * yScale) + 5, textPaint); // 文字
		}
		//
		// if (xData != null) {
		// if (currentX > 0 && currentX <= xData.length) {
		// canvas.drawRect(xPoint + (currentX - 0.5f) * xScale, border, xPoint +
		// (currentX + 0.5f) * xScale, viewHeight
		// - yPoint, selectBkgPaint);
		// canvas.drawText(getPrettyNumber(df.format(Float.parseFloat(yData[currentX
		// - 1]))) + yunit, xPoint
		// + (currentX - 0.25f) * xScale, YCoord(yData[currentX - 1]) - 40,
		// dataPaint);
		// }
		// }
		if (xData != null) {
			for (int i = 0; i < xData.length; i++) {
				canvas.drawRect(xPoint + (i + 1) * xScale, border, xPoint + (i + 1) * xScale, viewHeight - yPoint, selectBkgPaint);
				canvas.drawText(getPrettyNumber(df.format(Float.parseFloat(yData[i]))) + yunit, xPoint + (i + 0.8f) * xScale,
						YCoord(yData[i]) - 10, dataPaint);
			}
		}

		canvas.drawText("0", xPoint - 10, viewHeight - yPoint + (12 * density), textPaint); // 文字
		if (xData != null) {
			for (int i = 0; i < xData.length; i++) {
				// 柱状图
				canvas.drawLine(xPoint + (i + 1) * xScale, viewHeight - yPoint, xPoint + (i + 1) * xScale, YCoord(yData[i]),
						dataPaint);
				// X轴显示的刻度值
				if (density >= 3) {
					canvas.drawText(xData[i], xPoint + (i + 1) * xScale - (xData[i].length() * 5 * density), viewHeight - yPoint
							+ (12 * density), textPaint); // 文字
				} else {
					canvas.drawText(xData[i], xPoint + (i + 1) * xScale - (xData[i].length() * 5 * density), viewHeight - yPoint
							+ (12 * density), textPaint); // 文字
				}
			}
		}
	}

	/**
	 * 初始化数据
	 */
	public void initData() {
		eachYLable = max(yData);
		if (getArrayLength(yData) == 0) {
			xPoint = 40;
		} else {
			xPoint = ((eachYLable * yScaleNum + "").length() + yunit.length()) * 8;
		}
		yPoint = 40;
		textSize = 10;
		xPoint = xPoint * density;
		yPoint = yPoint * density;
		xLength = viewWidth - xPoint - border;
		yLength = viewHeight - yPoint - border;
		yScale = yLength / (yScaleNum + 1);
		textSize = textSize * density;
		if (xData != null) {
			xScale = xLength / (xData.length + 1);
		}
	}

	/**
	 * 初始化所有画笔
	 */
	private void initPaint() {

		// 线的画笔
		linePaint = new Paint();
		linePaint.setStyle(Paint.Style.FILL);
		linePaint.setAntiAlias(true);// 去锯齿
		linePaint.setStrokeWidth(density * 1.3f);
		linePaint.setColor(Color.parseColor("#C7C7CC"));// 颜色

		// 文本的画笔
		textPaint = new Paint();
		textPaint.setStyle(Paint.Style.FILL);// 设置画笔风格
		textPaint.setAntiAlias(true);// 去锯齿
		textPaint.setColor(Color.parseColor("#939393"));// 颜色
		textPaint.setTextSize(textSize); // 设置轴文字大小

		// 曲线和未选中圆点的画笔
		dataPaint = new Paint();
		dataPaint.setStyle(Paint.Style.FILL);
		dataPaint.setAntiAlias(true);// 去锯齿
		dataPaint.setColor(Color.parseColor("#009BDF"));// 颜色
		dataPaint.setTextSize(textSize); // 设置轴文字大小
		dataPaint.setStrokeWidth(density * 30);// 宽度

		// 选中之后月份背景的画笔
		selectBkgPaint = new Paint();
		selectBkgPaint.setStyle(Paint.Style.FILL);
		selectBkgPaint.setAntiAlias(true);// 去锯齿
		selectBkgPaint.setColor(Color.parseColor("#00000000"));// 颜色
		selectBkgPaint.setTextSize(textSize); // 设置轴文字大小
	}

	/**
	 * 得到数组中单元字符串的长度
	 * 
	 * @param array
	 * @return
	 */
	public int getArrayLength(String[] array) {
		int length = 0;
		if (array == null) {
			return length;
		}
		for (int i = 0; i < array.length; i++) {
			if (i == 0) {
				length = array[0].length();
			} else {
				if (array[i].length() > array[i - 1].length()) {
					length = array[i].length();
				}
			}
		}
		return length;
	}

	/**
	 * 去掉数字末尾多余的0
	 * 
	 * @param number
	 * @return
	 */
	public String getPrettyNumber(String number) {
		if (Double.parseDouble(number) == 0) {
			return "0";
		} else {
			return BigDecimal.valueOf(Double.parseDouble(number)).stripTrailingZeros().toPlainString();
		}
	}

	/**
	 * 计算Y坐标
	 * 
	 * @param y0
	 * @return
	 */
	private float YCoord(String y0) // 计算绘制时的Y坐标，无数据时返回-999
	{
		float y;
		try {
			y = Float.parseFloat(y0);
		} catch (Exception e) {
			return -999; // 出错则返回-999
		}
		try {
			// YScale/eachYLabel为比率 乘以y得到距离圆点的距离
			return (float) viewHeight - yPoint - ((y / eachYLable) * yScale);
		} catch (Exception e) {
		}
		return y;
	}

	/**
	 * 计算Y轴坐标的最大值
	 * 
	 * @param p
	 * @return
	 */
	public float max(String[] p) {
		if (p == null) {
			return 0;
		}
		float max = 0;
		for (int i = 0; i < p.length; i++) {
			if (Float.parseFloat(p[i]) - max > 0) {
				max = Float.parseFloat(p[i]);
			}
		}
		int length = (int) (max) / 20 + 1;// 为了取整数 比如最大值为39的时候 返回40
		return (float) (Math.round(length * 20 / yScaleNum));
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			currentX = Math.round((event.getX() - xPoint) / xScale);
			postInvalidate();
			break;
		case MotionEvent.ACTION_UP:
			int currentXMove = Math.round((event.getX() - xPoint) / xScale);
			if (event.getY() >= 0 && event.getY() <= getHeight()) {
				if (currentX == currentXMove && xData != null) {
					if (currentX > 0 && currentX <= xData.length && listener != null) {
						listener.onClick(currentX - 1);
					}
				}
			}
			break;
		}

		return true;
	}

	public void setOnGraphItemClickListener(OnGraphItemClickListener listener) {
		this.listener = listener;
	}

	public interface OnGraphItemClickListener {
		public void onClick(int position);
	}

}
